package com.orange.controller;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.orange.dbhelp.page.Page;
import com.orange.handler.AuthRectificationReportService;
import com.orange.handler.expert.AuthGroupService;
import com.orange.modules.bean.SessionUser;
import com.orange.modules.entity.AuthRectificationReport;
import com.orange.modules.entity.expert.AuthExam;
import com.orange.modules.entity.expert.AuthGroup;
import com.orange.util.AppConfig;
import com.orange.util.ReturnCode;

@Controller
@RequestMapping("/rectification")
public class AuthRectificationReportController extends BaseController{

	private static final Logger log = Logger.getLogger(AuthRectificationReportController.class);
	
	@Autowired
	private AppConfig appconfig;
	
	@Autowired
	private AuthRectificationReportService authRectificationReportService;
	
	@Autowired
	private AuthGroupService authGroupService;
	
	/**
	 * 查询整改报告
	 */
	@RequestMapping(value = "/queryAuthRectificationReport" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> queryAuthRectificationReport(HttpServletRequest request) {
		String sid = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(sid == null){
			return toResponse(null, ReturnCode.FAIL, "未登录");
		}
		try {
			AuthRectificationReport rr = authRectificationReportService.findRectificationReportBySchoolId(sid);
			if(rr == null)
				return toResponse(null, ReturnCode.SUCCESS, "暂无数据");
			return toResponse(rr, ReturnCode.SUCCESS, "查询成功!");
		} catch (SQLException e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "查询失败!");
		}
	}
	
	/**
	 * 整改报告上传
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/uploadReport" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(
			@RequestParam("file")MultipartFile filedata
			){
		try {
			String returnDatasUrl = null;
	  		String datasfile = appconfig.getFilePath();
	  		
	  		//取得可上传的文件类型  
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));
	  		
	  		String fileName = filedata.getOriginalFilename();  
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
	  		//对扩展名进行小写转换  
	  		ext = ext.toLowerCase();  
	  		/*//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
	  				(int)(Math.random()*10000) + "." + ext;*/
	  		File file = null;
	  		if(!fileTypes.contains(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024>appconfig.getFileSize()){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}
	  		
	  		Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();
            String pathbig=datasfile+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
				
		    returnDatasUrl = y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
			return toResponse(returnDatasUrl,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			log.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	   private List<String> arrayToList(String[] strs){
	    	List<String> list=new ArrayList<String>();
	    	if(strs.length>0){
	    		for(int a =0;a<strs.length;a++){
	    			list.add(strs[a].toString().trim());
	    		}
	    	}
			return list;
	    }
	   
	/**
	 * 保存地址path   
	 */
	@RequestMapping(value = "/saveAuthRectificationReport" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveAuthRectificationReport(HttpServletRequest request,@RequestBody Map<String,String> map){
		String filePath = map.get("filepath");
		String fileName = map.get("filename");
		if(filePath == null || fileName ==null || StringUtils.isBlank(filePath) || StringUtils.isBlank(fileName)){
			return toResponse(null, ReturnCode.FAIL, "参数不能为空!");
		}
		
		String sid = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(sid== null){
			return toResponse(null, ReturnCode.FAIL, "未登录!");
		}
		String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

  		Calendar cal=Calendar.getInstance();
        int y=cal.get(Calendar.YEAR);
		
		try {
			AuthGroup ag = authGroupService.queryAuthGroupBySchoolId(sid);
			if(!("3").equals(ag.getState())){
				return toResponse(null, ReturnCode.FAIL, "现场考察还未结束!");
			}
			
			AuthRectificationReport rr = authRectificationReportService.findRectificationReportBySchoolId(sid);
			if(rr != null){
				authRectificationReportService.deleteRectificationReport(rr.getPid());
			}
			
			AuthRectificationReport arr = new AuthRectificationReport();
			arr.setSchoolId(sid);
			arr.setFileName(fileName);
			arr.setFilePath(filePath);
			arr.setCreateTime(nowTime);
			arr.setYear(y);
			arr.setState("2");
			authRectificationReportService.saveRectificationReport(arr);
			return toResponse(null, ReturnCode.SUCCESS, "保存成功!");
		} catch (SQLException e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "保存失败!");
		}
	}
	   
	   
	/**
	 * 下载文档
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/downloadFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public void downloadFile(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid){
		
		try {
			AuthRectificationReport rr=authRectificationReportService.findOne(pid);
			if(null==rr){
				return;
			}
			//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
	        String path = appconfig.getFilePath();  
	        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
	        String filepath= rr.getFilePath();
	        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
	        filename = java.net.URLEncoder.encode(filename, "UTF-8");
	        
	        response.setHeader("Content-Type","application/msexcel");
	        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        
	        ServletOutputStream out;  
	        File file = new File(path +filepath);  
	  
	            FileInputStream inputStream = new FileInputStream(file);  
	  
	            //3.通过response获取ServletOutputStream对象(out)  
	            out = response.getOutputStream();  
	            
	            byte[] buffer = new byte[512];  
	            int count = 0;
		         while ((count = inputStream.read(buffer)) > 0) {
		        	 out.write(buffer, 0, count);
		         } 
	            inputStream.close();  
	            out.close();  
	            out.flush();  
	  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}   
	   
	/**
	 * 管理员页面--查询所有学校的所有整改报告   
	 */
	@RequestMapping(value = "/queryAllRectificationReport" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> queryAllRectificationReport(HttpServletRequest request,@RequestBody Map<String,String> map) {
		String pageNumber = map.get("pageNumber");
		String pageSize = map.get("pageSize");
		if(null == pageNumber || null == pageSize || StringUtils.isBlank(pageSize) || StringUtils.isBlank(pageNumber))
			return toResponse(null, ReturnCode.FAIL, "参数为空!");
		try {
			Page<AuthRectificationReport> page = authRectificationReportService.queryAllReport(map);
			if(page == null){
				return toResponse(null, ReturnCode.SUCCESS, "暂无数据!");
			}
			return toResponse(page, ReturnCode.SUCCESS, "分页查询成功");
		} catch (SQLException e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "分页查询失败");
		}	
	}   
}
